<?php
/**
 * Trida pro praci s nemovitosti. Umoznuje nemovitost importovat pres
 * data publisher API a ulozit do databaze.
 *
 * @author David Dusek
 */
class EstateImport {
    /**
     * XML retezec do ktereho se uklada odpoved z API
     * @var string 
     */
    private $XMLString = null;    
    
    /**
     * Instance tridy DataRequest pro odesilani pozadavku na API data publisheru
     * @var DataRequest 
     */
    private $dataRequest = null;
    
    /**
     * Pripojeni k databazi.
     * @var NConnection 
     */
    private $db = null;    
       
    /**
     * Seznam id menovitosti.
     * @var array 
     */
    private $estateIdList = array();
    
    /**
     * Data pro jednu konkretni nemovitost.
     * @var array
     */
    public $data = array();
    
    /**
     * Seznam id fotek pro nemovitost.
     * @var array 
     */
    public $photos = array();
    
    /**
     * Vychozi kontruktor.
     * @param NConnection $db
     */
    public function __construct($db) {
        $this->dataRequest = new DataRequest();
        $this->db = $db;        
    }
    
    /**
     * Ziskani seznamu id nemovitosti.
     * @return array 
     */
    public function getEstateIdList() {
        if (empty($this->estateIdList)) {
            $this->getEstateList();
        }
        
        return $this->estateIdList;
    }
    
    public function updateAllEstates() {
        if ($this->getEstateList()) {                        
            foreach ($this->estateIdList as $estateId) {
                if ($this->getEstateInformation($estateId)) {
                    $table = new EstateModel($this->db);
                    $table->where("id = ?", $estateId)->update(array(
                        "price_inc_comm" => $this->data["price_inc_comm"]
                            ));
                }                
            }
        }
    }
    
    /**
     * Metoda importuje vsechny neovitosti do databaze. Pokud najde zaznam 
     * v databazi, tak ho updatuje a pokud se jedna o novy zaznam tak ho vlozi.
     * Tato metoda by mela byt pouzita pouze pro inicializaci databaze. Dalsi
     * zmeny jsou provadeny pomoci synchronizacniho skriptu a volani metody
     * import pro jednu nemovitost (nabidku).
     */
    public function importAllEstates() {    
        if ($this->getEstateList()) {                        
            foreach ($this->estateIdList as $estateId) {
                $this->importEstate($estateId);
            }
        }
    }
    
    /**
     * Import jedne nemovitosti do databaze.
     * @param int $id id nemovitosti
     */
    public function importEstate($id) {
        if ($this->getEstateInformation($id)) {            
            // importujeme maklere
            $agentImport = new AgentImport($this->db);
            $agentImport->importAgent($this->data["agent"]);            
            
            $table = new EstateModel($this->db);
            if ($table->get($id)) {
                $this->data['deleted'] = false;
                $table->where("id", $id)->update($this->data);
            } else {
                $table->insert($this->data);
            }            
            
            $pictureImport = new PictureImport($this->db);
            $pictureModel = new PictureModel($this->db);
            $pictureModel->deleteDiff($id, array_keys($this->photos));
            foreach ($this->photos as $photoId => $photoData) {
                $pictureImport->importImage($photoId, $id, $photoData["description"], $photoData["order"]);
            } 
        }
    }
    
    /**
     * Metoda odesle pozadavek na API s zadosti o seznam nemovitosti. Vysledkem
     * je seznam id nemovistosti v atributu estateIdList.
     * @return bool true pri uspechu jinak false 
     */
    private function getEstateList() {
        $parametrs = array(
            "Login"    => DataRequest::$login,
            "Password" => DataRequest::$password
        );
        
        // odeslani pozadavku do na API
        $this->XMLString = $this->dataRequest->sendRequest($parametrs, 
                DataRequest::$pathEstateIdList);        
        
        // rozparsovani XML seznamu nemovitosti
        if ($this->parseEstateList()) {
            return true;
        }
        return false;
    }
    
    /**
     * Metoda rozparsuje xml ulozene v atributu XMLString a ulozi vysledny
     * seznam Id do pole estateIdList.
     * @return bool true pokud je mozne rozparsovat jinak false 
     */
    private function parseEstateList() {
        if ($this->XMLString === null) {
            return false;
        }
        
        $document = simplexml_load_string($this->XMLString);
        if ($document) {        
            $this->estateIdList = array();
            foreach ($document->Data->apiIdWithStamp as $item) {            
                $this->estateIdList[] = (int) $item->Id;
            }
        } else {
            return false;
        }
//        var_dump($this->estateIdList);
        return true;
    }
    
    /**
     * Ziskani informaci o nemovitosti prostrednictvim api. Vysledny XML je
     * ulozen v atributu XMLString.
     * @param int $id id nemovitosti
     * @return bool true pokud se dotaz podari jinak false 
     */
    private function getEstateInformation($id) {
        $parametrs = array(
            "Login"    => DataRequest::$login,
            "Password" => DataRequest::$password,
            "EstateId" => $id
        );
        
        // odeslani pozadavku do na API
        $this->XMLString = $this->dataRequest->sendRequest($parametrs, 
                DataRequest::$pathEstate);
//        echo $this->XMLString;
        
        // rozparsovani XML seznamu nemovitosti
        if ($this->parseEstateInformation()) {
            return true;
        }
        return false;
    }
    
    /**
     * Rozparsovani informaci o nemovitosti a vlozeni do atributu data.
     * @return true pokud se parsovani zdari jinak false 
     */
    private function parseEstateInformation() {
        if ($this->XMLString === null) {
            return false;
        }
        
        $document = simplexml_load_string($this->XMLString);
        if ($document) {                    
            $this->data = array(
                "id"                    => (int) $document->Data->Id,
                "registration_number"   => (int) $document->Data->RegistrationNumber, // cislo zakazky z RealStudia
                "agent"                 => (int) $document->Data->AgentId, // agent ktery ma nemovitost na starosti
                "estate_type"           => (int) $document->Data->TypeOfRealEstate->NumberValue, // typ nemovitosti
                "estate_subtype"        => (int) $document->Data->SubtypeOfRealEstate->NumberValue, // podtyp nemovitosti
                "commission_type"       => (int) $document->Data->TypeOfCommission->NumberValue, // typ nabidky
                "commission_status"     => (int) $document->Data->StatusOfCommission->NumberValue, // stav nabidky
                "title"                 => (string) $document->Data->Title, // titulek nabidky
                "description"           => (string) $document->Data->Description, // popis nabidk
                "region"                => (string) $document->Data->Lc3Name, // kraj
                "zone"                  => (string) $document->Data->Lc4Name, // okres
                "town"                  => (string) $document->Data->Lc5Name, // obec
                "street"                => (string) $document->Data->Lc9Name, // ulice
                "district"              => (string) $document->Data->Lc10Name, // ctvrt
                "post_code"             => (string) $document->Data->Lc11Name, // psc
                "house_number"          => (int) $document->Data->Lc12Name, // cislo domu
                "price_type"            => (string) $document->Data->TypeOfPrice->StringValue, // typ ceny celkem nebo za metr
                "price"                 => (double) $document->Data->Price, // cena a predpoklada se ze v Kc
                "price_inc_comm"        => ((string) $document->Data->PriceIncludeCommission) == "true" ? 1 : 0, // obsahuje cena provizi pro RK
                "currency"              => (string) $document->Data->Currency->StringValue, // mena
                "area_use"              => (int) $document->Data->AreaUse, // uzitna plocha         
                "area_of_lot"           => (int) $document->Data->AreaOfLot, // plocha parcely
                "electricity"           => (string) $document->Data->Electricity->StringValue, // typ elektickeho pripojeni
                "canalization"          => (string) $document->Data->Canalization->StringValue, // typ kanalizace
                "gas"                   => (string) $document->Data->Gas->StringValue, // typ kanalizace
                "water"                 => (string) $document->Data->Water->StringValue, // typ vodovodni pripojky   
                "disposition"           => (int) $document->Data->Disposition->NumberValue, // dispozice
                "building_structure"    => (string) $document->Data->StructureOfBuilding->StringValue, // konstrukce
                "aboveground_floor"     => (int) $document->Data->NumberOfAbovegroundFloor, // pocet nadzemnich podlazi
                "underground_floor"     => (int) $document->Data->NumberOfUndergroundFloor, // pocet podzemnich podlazi
                "estate_status"         => (int) $document->Data->StatusOfEstate->NumberValue, // stav budovy
                "ownership_type"        => (string) $document->Data->TypeOfOwnership->StringValue, // typ vlastnictvi                
                "floor"                 => (string) $document->Data->Floor->StringValue, // patro - POZOR pocet podlazi = pater + 1 (+ 1 je prizemi)
                "floor_area"            => (double) $document->Data->AreaFloor, // plocha podlazi u bytu
                "electricity_on_lot"    => (string) $document->Data->ElectricityOnLot->StringValue, // elektrina na pozemku
            );
            
            // parsovani obrazku nemovitosti            
            $this->photos = array();
            foreach ($document->Data->Fotos->apiDocument as $photo) {                
                $this->photos[(int)$photo->FileDataId]["description"] = (string)$photo->Description;
                $this->photos[(int)$photo->FileDataId]["order"] = (int)$photo->Order;
            }
        } else {
            return false;
        }
        return true;
    }
    
    /**
     * Metoda pro testovani pozadavku.
     * @param int $id id nemovitosti
     * @return String 
     */
    public function getXMLData($id) {
        $this->getEstateInformation($id);
        return $this->XMLString;
    }
}

